package com.kitty.record.kittyjava.juc;

import sun.security.krb5.internal.Ticket;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description
 * @Author SHEN
 * @Date 2021/1/12
 */
public class ThreadDemo {

    public static void main(String[] args) {

        //SynTicket ticket = new SynTicket();
        LockTicket ticket = new LockTicket();

        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"窗口A").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"窗口B").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"窗口B").start();
    }
}

class SynTicket {

    private int num = 30;

    public synchronized void sale(){

        if(num > 0){
            System.out.println(Thread.currentThread().getName()+"卖了第"+num+"张票，剩余"+--num+"张票");
        }
    }
}

class LockTicket {

    private int num = 20;

    ReentrantLock lock = new ReentrantLock();

    public void sale(){
        lock.lock();
        try {
            if(num > 0){
                System.out.println(Thread.currentThread().getName()+"卖了第"+num+"张票，剩余"+--num+"张票");
            }
        } finally {
            lock.unlock();
        }
    }
}
